package com.zl.tcbnewcar.ui.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhy.autolayout.AutoRelativeLayout;
import com.zl.tcbnewcar.R;
import com.zl.tcbnewcar.base.BaseActivity;
import com.zl.tcbnewcar.base.UniversalAdapter;
import com.zl.tcbnewcar.base.UniversalViewHolder;
import com.zl.tcbnewcar.model.CarServerEntity;
import com.zl.tcbnewcar.model.ShareBean;
import com.zl.tcbnewcar.utils.API;
import com.zl.tcbnewcar.utils.HttpUtils;
import com.zl.tcbnewcar.utils.ShareUtils;
import com.zl.tcbnewcar.utils.SpUtlis;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;

/**
 * @author zhanglei
 * @date 18/3/21
 * 我的订阅服务
 */
public class SubServiceActivity extends BaseActivity {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.iv_title_share)
    ImageView ivTitleShare;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.sub_service_listView)
    ListView subServiceListView;
    @BindView(R.id.sub_service_trl)
    TwinklingRefreshLayout subServiceTrl;
    @BindView(R.id.tv_action)
    TextView tvAction;
    @BindView(R.id.null_arl)
    AutoRelativeLayout nullArl;
    private List<CarServerEntity> mList = new ArrayList<>();
    private int page = 1;
    private int mPosition = -1;
    private UniversalAdapter<CarServerEntity> mAdapter;
    private View viewBottom;
    private TextView tvBottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sub_service);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        subServiceTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                page = 1;
                getListData();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page++;
                        getListData();
                    }
                }, 800);
            }
        });
    }

    /**
     * 获取界面数据
     */
    private void getListData() {
        Map<String, String> params = new HashMap<>();
        params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
        params.put("page", page + "");
        HttpUtils.getInstance().Post(mActivity, params, API.getSubscriceList, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                Log.e("body", body);
                try {
                    if (page == 1) {
                        mList.clear();
                        subServiceTrl.finishRefreshing();
                    } else {
                        subServiceTrl.finishLoadmore();
                    }
                    JSONObject object = new JSONObject(body);
                    JSONArray array = object.optJSONArray("items");
                    for (int i = 0; i < array.length(); i++) {
                        CarServerEntity carDealerEntity = new Gson().fromJson(array.optJSONObject(i).optString("carServerEntity"), CarServerEntity.class);
                        mList.add(carDealerEntity);
                    }
                    mAdapter.notifyDataSetChanged();

                    if (mList.size() <= 0) {
                        nullArl.setVisibility(View.VISIBLE);
                    } else {
                        nullArl.setVisibility(View.GONE);
                    }

                    if (array.length() <= 0) {
                        if (subServiceListView.getFooterViewsCount() <= 0) {
                            tvBottom.setText("共" + mList.size() + "条服务信息");
                            subServiceListView.addFooterView(viewBottom);
                        }
                    } else {
                        if (subServiceListView.getFooterViewsCount() > 0) {
                            subServiceListView.removeFooterView(viewBottom);
                        }
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Request error, Exception e) {
                if (page == 1) {
                    mList.clear();
                    subServiceTrl.finishRefreshing();
                } else {
                    subServiceTrl.finishLoadmore();
                }
            }
        });
    }

    private void initData() {
        subServiceTrl.startRefresh();
    }

    private void initView() {

        tvTitleName.setText("服务关注");
        mAdapter = new UniversalAdapter<CarServerEntity>(mActivity, mList, R.layout.car_hang_list_item) {
            @Override
            public void convert(UniversalViewHolder holder, final int position, CarServerEntity s) {
                holder.getView(R.id.linear_bottom_two).setVisibility(View.VISIBLE);
                holder.getView(R.id.linear_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPosition = position;
                        new AlertDialog.Builder(mActivity).setMessage("是否删除该服务").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {

                            }
                        }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                delete();
                            }
                        }).show();
                    }
                });
                holder.getView(R.id.linear_share).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mPosition = position;
                        share();
                    }
                });
                holder.setText(R.id.tv_car_hang_name, s.getSerTitle());
                holder.setText(R.id.tv_car_data, s.getCity().getCityName());
                holder.setText(R.id.tv_car_hang_phone, "联系电话：" + s.getCarUser().getUserPhone());
                holder.setText(R.id.tv_car_hang_data, "简述：" + s.getSerContext());
                holder.setImageUrl(mActivity, R.id.iv_car_hang_icon, s.getSerImg());
                holder.setText(R.id.carForWard, s.getSerForWard() + "");
                holder.setText(R.id.tv_carBrowse, s.getSerBrowse() + "");
            }
        };
        subServiceListView.setAdapter(mAdapter);
        initProgress(subServiceTrl);

        viewBottom = LayoutInflater.from(mActivity).inflate(R.layout.tv_bottom_layout, null);
        tvBottom = viewBottom.findViewById(R.id.tv_bottom);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(mActivity).onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.iv_title_back, R.id.tv_action})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.tv_action:
                setResult(RESULT_OK, new Intent());
                finish();
                break;
        }
    }

    /**
     * 删除服务
     */
    private void delete() {
        Map<String, String> params = new HashMap<>();
        params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
        params.put("sid", mList.get(mPosition).getId() + "");
        HttpUtils.getInstance().Post(mActivity, params, API.subscriceServer, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                showToast("成功删除服务");
                mList.remove(mPosition);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    /**
     * 分享服务
     */
    private void share() {
        final CarServerEntity carDealerEntity = mList.get(mPosition);
        ShareBean shareBean = new ShareBean();
        shareBean.setShareTitle(carDealerEntity.getSerTitle());
        shareBean.setImgUrl(carDealerEntity.getSerImg());
        shareBean.setShareContent(carDealerEntity.getSerContext());
        shareBean.setUrl(API.toCarServer + "?sid=" + carDealerEntity.getId());
        ShareUtils.share(mActivity, shareBean, new ShareUtils.OnShareListener() {
            @Override
            public void shareSuccess(SHARE_MEDIA share_media) {
                showToast("分享成功");
                Map<String, String> params = new HashMap<String, String>();
//                params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
                params.put("sid", carDealerEntity.getId() + "");
                HttpUtils.getInstance().Post(mActivity, params, API.toForwardServer, new HttpUtils.OnOkHttpCallback() {
                    @Override
                    public void onSuccess(String body) {
                        Log.e("body", body);
                    }

                    @Override
                    public void onError(Request error, Exception e) {
                        Log.e("body", "");
                    }
                });
            }

            @Override
            public void shareError(SHARE_MEDIA share_media, Throwable throwable) {

            }
        });
    }
}
